//
//  HMRefreshView.swift
//  WeiBo
//
//  Created by apple on 16/6/29.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit

enum HMRefreshType: Int{
    
    case Normal = 0
    case Pulling = 1
    case Loading = 2
    
}

class HMRefreshView: UIControl {

    //定义一个属性,来记录状态
    // 给他一个默认值
    var type: HMRefreshType = .Normal{
    
        didSet{
            
            // 在didSet方法里实现效果
            switch type {
            case .Normal :
                print("正常状态")
                messageLabel.text = "下拉刷新"
                
                arrowImageView.hidden = false
                
                loadingView.stopAnimating()
                // 让箭头恢复一下
                self.arrowImageView.transform = CGAffineTransformIdentity
            case .Pulling :
                print("拖拽状态")
                messageLabel.text = "释放更新"
                // 让箭头转半圈
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    self.arrowImageView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                    
                })
            case .Loading:
                print("加载")
                messageLabel.text = "加载中..."
                
                arrowImageView.hidden = true
                
                loadingView.startAnimating()
                
                // 让 视图停了一下
                var inset = scrollView!.contentInset
                
                inset.top = inset.top + self.bounds.height
                
                scrollView?.contentInset = inset
                
                // 加载数据 -- 回调
                // 利用control的父类方法去调用 值改变的方法
                sendActionsForControlEvents(.ValueChanged)
                
                
            }
        }
        
    }
    
    // 定义成一个属性
    var scrollView: UIScrollView?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setupUI(){
        
        backgroundColor = RandomColor()
        
        // 1. 设置默认的宽高
        var frame = self.frame
        
        frame.size = CGSizeMake(kUIScreenWidth, 50)
        // 修改frame的y值
        frame.origin.y = -50
        
        self.frame = frame
        
        
        // 添加控件设置约束
        addSubview(arrowImageView)
        addSubview(messageLabel)
        addSubview(loadingView)
        
        arrowImageView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(-30)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(arrowImageView.snp_right).offset(HomeCellMargin)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        
        loadingView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(-30)
            make.centerY.equalTo(self.snp_centerY)
        }
    }
    
    // 这个方法会在控件添加到父控制的时候执行
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        print(newSuperview)
        
        // 我们可以把自己抽取的下拉刷新的类,拓展到 UIScrollView里
        
        if newSuperview is UIScrollView {
            
            scrollView = newSuperview as? UIScrollView
            
            // 添加KVO监听
            scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
            
        }
        
        
        
    }
    
    //MARK:-- 监听者需要现象属性的监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
//        print(scrollView?.contentOffset.y)
        
       
        
        // 拖拽的属性
        if scrollView!.dragging {
            
//            print("你拖拽我呢")
            if scrollView?.contentOffset.y < -140 && type == .Normal{
                
//                print("状态改变,变成 释放更新")
                // 记录一下状态
                type = .Pulling
                
            } else if scrollView?.contentOffset.y >= -140 && type == .Pulling{
                
//                print("状态改变 ,变成 下拉刷新")
                type = .Normal
            }
            
            // 当满足 释放更新的时候(type == .pulling) 我松手就可以去加载数据
            
        } else {
            
//            print("松手")
            // 判断加载的状态的时候,有一个提前
            if scrollView?.contentOffset.y < -140 && type == .Pulling{
                
//                print("状态改变,变成 加载中")
                // 记录一下状
                
                type = .Loading
            }
        }
    }
    
    //MARK:-- 仿照系统的下拉完成方法
    func endRefreshing(){
        
        // 问题是,当我们没有判断这个标记的时候, 第一网络请求之后,会执行一下这个操作,我们分析了一下,要想调用inset.top - 高度的方法,应该是他加载之后,既然是加载之后,我们就可以判断一下 type
        
        if type == .Loading {
            
            var inset = scrollView!.contentInset
            
            inset.top = inset.top - self.bounds.height
            
            scrollView?.contentInset = inset
            
        }
        
        // 改变一下状态
        type = .Normal
        
        
    }
    
    //MARK:-- 懒加载
///  箭头
    private lazy var arrowImageView: UIImageView = {
    
        let img = UIImageView()
        
        img.image = UIImage(named: "tableview_pull_refresh")
        
        return img
    }()
    ///提示语
    private lazy var messageLabel: UILabel = UILabel(text: "下拉刷新...", fontSize: 15, textColor: UIColor.darkGrayColor(), isSingleLine: true)
    ///提示加载菊花
    private lazy var loadingView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    

}
